package Chapter2;

public class Polynomial {
    private PolySinglyList<TermX> list;

    public Polynomial(boolean asc) {
        this.list = new PolySinglyList<TermX>(asc);
    }

    public Polynomial() {
        this(true);
    }

    public Polynomial(TermX[] termXES, boolean asc) {
        this(asc);
        for (int i=0;i< termXES.length;i++)
            list.insert(termXES[i]);
    }

    public Polynomial(String polystr) {
        this();
        if (polystr == null || polystr.length() == 0)
            return;
        Node<TermX> rear = this.list.head;
        int start = 0, end = 0;
        while (start < polystr.length() && end < polystr.length()) {
            int i = polystr.indexOf('+', end + 1);//返回字符+在字符串中从end+1开始的序号
            if (i == -1)
                i = polystr.length();
            int j = polystr.indexOf('-', end + 1);
            if (j == -1)
                j = polystr.length();
            end = i < j ? i : j;    //end为下一个+或-号的序号
            rear.next = new Node<TermX>(new TermX(polystr.substring(start, end)), null);
            //尾插入，以序号start～end的子串作为一项，创建结点，创建元素对象
            rear = rear.next;
            start = end;
        }
    }

    /**
     * 此拷贝方法不能复制二元的项
     *
     * @param poly
     */
    public Polynomial(Polynomial poly) {
        this(poly.list.asc);
        Node<TermX> rear = this.list.head;
        for (Node<TermX> p = poly.list.head; p != null; p = p.next) {
            rear.next = new Node<TermX>(new TermX(p.data), null);
            rear = rear.next;
        }
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        Node<TermX> p = this.list.head.next;
        Node<TermX> q = ((Polynomial) obj).list.head.next;

        while (p.data.equals(q.data) && q != null && p != null) {
            p = p.next;
            q = q.next;
        }
        return p == null && q == null;
    }

    public void addAll(Polynomial poly){
        this.list.addAll(poly.list);
    }

    public Polynomial union(Polynomial poly){
        Polynomial p=new Polynomial(this);
        p.addAll(poly);
        return p;
    }

    public Polynomial multi(Polynomial poly) {
        Polynomial all = new Polynomial();
        Node<TermX> p = this.list.head.next;
        Node<TermX> q = poly.list.head.next;
        Node<TermX> r = q;

        while (p != null) {
            while (q != null) {
                int i = p.data.coef * q.data.coef;
                int j = p.data.xexp + q.data.xexp;
                all.list.insert(new TermX(i, j));
                q = q.next;
            }
            p = p.next;
            q = r;
        }
        return all;
    }

    public String toString() {
        String str = "";
        for (Node<TermX> p = this.list.head.next; p != null; p = p.next)
            str += p.data.toString();
        return str + "," + (this.list.asc ? "升序" : "降序");
    }


}
